package com.example.demo.leetcode;

/**
 * 链接：<a href="https://leetcode.cn/problems/reverse-linked-list/?envType=study-plan-v2&envId=programming-skills">https://leetcode.cn/problems/reverse-linked-list/?envType=study-plan-v2&envId=programming-skills</a>
 *
 * @author WangYX
 * @version 1.0.0
 * @date 2024/01/30 14:10
 */
public class _206_反转链表 {
    public static void main(String[] args) {
        ListNode list1 = new ListNode(1, new ListNode(2, new ListNode(4)));
        ListNode list2 = new ListNode(1, new ListNode(3, new ListNode(4)));
        ListNode node = reverseList2(list1);
        System.out.println();

    }

    /**
     * 迭代
     */
    public static ListNode reverseList(ListNode head) {
        ListNode pre = new ListNode();
        while (head != null) {
            ListNode node = new ListNode(head.val);
            node.next = pre.next;
            pre.next = node;
            head = head.next;
        }
        return pre.next;
    }
    public static ListNode reverseList2(ListNode head) {
        ListNode pre = new ListNode(-1);
        while (head != null) {
            pre.next = new ListNode(head.val, pre.next);
            head = head.next;
        }
        return pre.next;
    }

    /**
     * 递归
     * @param head
     * @return
     */
    public static ListNode reverseList1(ListNode head) {
        ListNode pre = new ListNode();
        reverse(pre, head);
        return pre.next;
    }

    private static void reverse(ListNode pre, ListNode head) {
        if (head != null) {
            ListNode node = new ListNode(head.val);
            node.next = pre.next;
            pre.next = node;
            reverse(pre, head.next);
        }
    }
}
